<template>
  <div class="teacherbox">
    <!-- 头部 -->
    <el-row>
      <el-col :span="24" class="top">
        <span class="title">师资管理</span>
        <div class="btn">
          <!-- 批量添加 -->
          <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3"
            :on-exceed="handleExceed" :file-list="fileList">
            <el-button style="font-size: 13px" class="add" v-show="isButton(44)">批量添加</el-button>
            <template #tip></template>
          </el-upload>
          <!-- 添加 -->
          <el-button type="primary" style="font-size: 13px" @click="addTeaCher" class="add" v-show="isButton(44)">添加教资
          </el-button>
        </div>
      </el-col>
    </el-row>
    <!-- 添加对话框 -->
    <div>
      <el-dialog :close-on-click-modal="false" v-model="dialogVisible" title="添加老师" width="40%"
        :before-close="handleClose" v-if="dialogVisible">
        <div class="addInfo">
          <el-form ref="formRef" :model="ruleForm" status-icon label-width="120px" class="demo-ruleForm">
            <el-form-item label="姓名" :rules="[{ required: true, message: '请输入姓名' }]" prop="name">
              <el-input style="width: 350px" v-model="ruleForm.name" type="text" />
            </el-form-item>
            <el-form-item label="电话" prop="tel">
              <el-input style="width: 350px" v-model="ruleForm.tel" type="text" />
            </el-form-item>
            <el-form-item label="部门" prop="depid" :rules="[{ required: true, message: '请选择部门' }]">
              <div class="example-block">
                <el-cascader v-model="ruleForm.depid" :props="{ value: 'id', label: 'name' }" placeholder="请选择部门"
                  :options="listOptions" @change="handleChange" />
              </div>
            </el-form-item>
            <el-form-item label="角色" prop="roleid" :rules="[{ required: true, message: '请选择角色' }]">
              <el-select v-model="ruleForm.roleid" class="m-2" placeholder="请选择角色">
                <el-option v-for="item in Role" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="账号" prop="username" :rules="[{ required: true, message: '请输入账号' }]">
              <el-input style="width: 350px" v-model="ruleForm.username" type="text" />
            </el-form-item>
            <el-form-item label="密码" prop="pass" :rules="[
              { required: true, message: '请输入密码' },
              {
                min: 6,
                max: 16,
                message: '请输入6-16位的密码',
                trigger: 'blur',
              },
            ]">
              <el-input style="width: 350px" v-model="ruleForm.pass" show-password type="text" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel(formRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 搜索 -->
    <el-row class="search">
      <span style="color: dimgrey; font-size: 14px; margin: 7px 13px 7px 0px">关键字</span>
      <el-col :span="24">
        <el-input v-model="keys" placeholder="请输入关键字" class="int" />
      </el-col>
      <!-- 级级联动 -->
      <div class="example-block">
        <span class="example-demonstration">部门</span>
        <el-cascader v-model="ruleForm.depname" placeholder="请选择" :options="listOptions"
          :props="{ value: 'id', label: 'name' }" @change="searchChange" />
      </div>
      <!-- 选择器 -->
      <div>
        <span style="color: dimgrey; font-size: 14px; margin: 0 13px">角色</span>
        <el-select v-model="value" clearable placeholder="请选择">
          <el-option v-for="item in Role" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </div>
      <el-col :span="24">
        <el-button type="primary" style="margin-left: 12px; font-size: 13px" @click="search">搜索</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <div class="buttom">
      <!-- 列表展示 -->
      <el-row>
        <el-col :span="24">
          <el-table v-loading="loading" :data="tableData" empty-text="暂无数据"
            :header-cell-style="{ background: '#fafafa' }" key="id" style="width: 100%; font-size: 13px">
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="depname" label="部门" />
            <el-table-column prop="tel" label="电话" />
            <el-table-column prop="rolename" label="角色" />
            <el-table-column prop="username" label="账号" />
            <el-table-column fixed="right" label="操作" width="190" v-if="isButton(46) || isButton(47)">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="talkPass(scope.row)" v-if="isButton(46)">重置密码
                </el-button>
                <el-button link type="primary" size="small" @click="edit(scope.row)" v-if="isButton(46)">修改</el-button>
                <el-button link type="primary" size="small" @click="del(scope.row.id)" v-if="isButton(47)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:currentPage="params.page" v-model:page-size="params.psize"
          :page-sizes="[10, 20, 50, 100]" :small="small" :disabled="disabled" background
          layout="total, sizes, prev, pager, next, jumper" :total="count" @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </div>
    <!-- 重置密码对话框 -->
    <div class="reset">
      <el-dialog width="40%" :close-on-click-modal="false" v-model="resetPass" title="重置密码">
        <el-form ref="formRef" :model="ruleForm" :rules="rules" class="resetform" label-width="80px">
          <el-form-item label="姓名" prop="name">
            <span>{{ ruleForm.name }}</span>
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input v-model="ruleForm.pass" type="password" autocomplete="off" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPass">
            <el-input v-model="ruleForm.confirmPass" type="password" autocomplete="off" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel(formRef)">取消</el-button>
            <el-button type="primary" @click="confirm(formRef)">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 修改对话框 -->
    <div class="edit">
      <el-dialog v-model="editData" title="修改老师" width="40%" :close-on-click-modal="false" :show-close="true"
        v-if="editData" :before-close="handleClose">
        <div>
          <el-form ref="formRef" :model="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="姓名" :rules="[{ required: true, message: '请输入姓名' }]" prop="name">
              <el-input style="width: 350px" v-model="ruleForm.name" type="text" />
            </el-form-item>
            <el-form-item label="电话" prop="tel">
              <el-input style="width: 350px" v-model="ruleForm.tel" type="text" />
            </el-form-item>
            <el-form-item label="部门" :rules="[{ required: true, message: '请选择部门' }]" prop="depid">
              <div class="example-block">
                <el-cascader v-model="ruleForm.depid" placeholder="请选择部门" :props="{ value: 'id', label: 'name' }"
                  :options="listOptions" @change="updaChange" />
              </div>
            </el-form-item>
            <el-form-item label="角色" prop="roleid" :rules="[{ required: true, message: '请选择角色' }]">
              <el-select v-model="ruleForm.roleid" class="m-2" placeholder="请选择角色">
                <el-option v-for="item in Role" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel(formRef)">取消</el-button>
            <el-button type="primary" @click="upda(formRef)">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang='ts' setup>
// 引入列表展示调接口
import {
  listInfo,
  addInfo,
  jiList,
  delInfo,
  changePass,
  role,
} from "../../apis/teacher/listInfo";
// 引入页面css样式
import "../../static/css/teacher/teacher.css";
// 引入批量上传文件
import { ref, reactive, toRefs, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, UploadUserFile, FormInstance } from "element-plus";
import { getParentIdList } from "../../utils/treeUtils";
// 权限控制按钮是否隐藏方法导入
import { isButton } from "../../utils/isButton";

// 批量添加
const fileList = ref<UploadUserFile[]>([]);

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfert of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};
// 清空方法
const empty = () => {
  (ruleForm.username = ""),
    (ruleForm.pass = ""),
    (ruleForm.name = ""),
    (ruleForm.tel = ""),
    (ruleForm.depid = []),
    (ruleForm.roleid = ""),
    (ruleForm.searchDepa = []);
  ruleForm.confirmPass = ''
};
// 弹出框
const dialogVisible = ref(false);
const editData = ref<boolean>(false);
// 添加叉号
const handleClose = (formEl: FormInstance | undefined) => {
  dialogVisible.value = false;
  editData.value = false;
  resetPass.value = false;
  empty();
  listShow();
};
// 非空验证
const formRef = ref<FormInstance>();
const ruleForm: any = reactive({
  username: "",
  pass: "",
  name: "",
  tel: "",
  depid: [],
  roleid: "",
  searchDepa: [],
  id: 0
});
// 修改添加确认调接口
const modify = async () => {
  const res: any = await addInfo({
    id: ruleForm.id,
    username: ruleForm.username,
    pass: ruleForm.pass,
    name: ruleForm.name,
    tel: ruleForm.tel,
    depid: ruleForm.depid[ruleForm.depid.length - 1],
    roleid: ruleForm.roleid,
  });
  if (res.errCode === 10000) {
    ElMessage.success(tips.value);
    editData.value = false;
    dialogVisible.value = false
    listShow();
    empty();
  } else {
    ElMessage.error(res.errMsg);
  }
};
// 确认添加按钮
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      modify()
    } else {
      return false;
    }
  });
};
// 点击添加弹出框
const addTeaCher = () => {
  dialogVisible.value = true;
  tips.value = '添加成功'
}
// 编辑按钮
const updaChange = (e: any) => {
  ruleForm.depid = e;

};
const edit = (e: any) => {
  editData.value = true;
  ruleForm.name = e.name;
  ruleForm.id = e.id;
  ruleForm.tel = e.tel;
  ruleForm.depid = getParentIdList(listOptions.value, e.depid);
  ruleForm.roleid = e.roleid;
  ruleForm.oldpass = e.pass;
  ruleForm.username = e.username;
  tips.value = '修改成功'
};
// 点击取消
const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
  editData.value = false;
  resetPass.value = false;
  listShow();
  empty();
};
const upda = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      modify();
    } else {
      return false;
    }
  });
};
// 删除
const dele = async (id: any) => {
  const res: any = await delInfo({ id });
  // console.log(res);
  if (res.errCode === 10000) {
    ElMessage.success("删除成功!");
    listShow();
  } else {
    ElMessage.error("删除失败");
  }
};
const del = (ids: any) => {
  ElMessageBox.confirm("确定要删除该账号吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then((res) => {
      dele(ids);
    })
    .catch((error) => {
      ElMessage.error("已取消删除");
    });
};
// 搜索
const searchChange = (e: any) => {
  ruleForm.searchDepa = e;
};
const keys = ref("");
const search = () => {
  listShow();
};
const value = ref([]);
const handleChange = (value: any) => {
  ruleForm.depid = value;
};
// 调联动接口
const linkage = async () => {
  const res: any = await jiList();
  // console.log(res);
  if (res.errCode === 10000) {
    listOptions.value = res.data.list;
  }
};
// 定义的数据
var count = ref(0);
const data: any = reactive({
  // 角色数据
  Role: [],
  // 表格数据
  tableData: [],
  // 分页
  params: { page: 1, psize: 10 },
  // 三级联动数据
  listOptions: [],
  // 加载
  loading: true,
  // 提示
  tips: '添加成功'
});
const { tableData, params, listOptions, Role, loading, tips } =
  toRefs(data);
// 列表展示
const listShow = async () => {
  loading.value = true;
  const res: any = await listInfo({
    ...params.value,
    depid: ruleForm.searchDepa[ruleForm.searchDepa.length - 1],
    key: keys.value,
  });
  // console.log(res);
  if (res.errCode === 10000) {
    tableData.value = res.data.list;
    count.value = res.data.counts;
    loading.value = false;
  } else {
    ElMessage.error("加载失败！！！");
  }
};
// 角色列表
const roleList = async () => {
  const res: any = await role();
  // console.log(res);
  if (res.errCode === 10000) {
    Role.value = res.data.list;
  }
};
onMounted(() => {
  // 页面数据
  listShow();
  // 联动数据
  linkage();
  // 角色列表
  roleList();
});
// 重置密码
const resetPass = ref<boolean>(false);
const talkPass = (e: any) => {
  empty();
  (resetPass.value = true), (ruleForm.name = e.name);
  ruleForm.oldpass = e.pass;
  ruleForm.id = e.id;
  ruleForm.username = e.username;
  ruleForm.tel = e.tel;
  ruleForm.depid = e.depid;
  ruleForm.roleid = e.roleid;
  ruleForm.qq = e.pass;
};
// 密码验证
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (ruleForm.pass !== "") {
      if (!formRef.value) return;
      formRef.value.validateField("checkPass", () => null);
    }
    callback();
  }
};
const validateConfirmPass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== ruleForm.pass) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
};
const rules = reactive({
  pass: [{ validator: validatePass, trigger: "blur", required: true }, { min: 6, max: 16, message: '请输入6-16位的密码', trigger: 'blur' }],
  confirmPass: [{ validator: validateConfirmPass, trigger: "blur", required: true }],
});
// 重置密码调接口
const confirm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (ruleForm.id) {
        changePass(ruleForm).then((res: any) => {
          if (res.errCode === 10000) {
            resetPass.value = false;
            ElMessage.success("重置成功");
            listShow();
            empty();
          } else {
            ElMessage.error(res.errMsg);
          }
        });
      }
    } else {
      return false;
    }
  });
};
// 分页
const small = ref<boolean>(false);
const disabled = ref<boolean>(false);
// 条数
const handleSizeChange = (val: number) => {
  params.value.psize = val;
  listShow();
};
// 页数
const handleCurrentChange = (val: number) => {
  params.value.page = val;
  listShow();
};
</script>
